package dome_002;

/**
 * <p>Description: [synchronized关键字,对某个对象加锁]</p>
 * Created on 2020/12/3
 *
 * @author <a href="mailto: 819712047@qq.com">谢振东 </a>
 * @version 1.0
 */
public class Demo002_03 {

    private int count = 10;

    public synchronized void test() {
        //等同于synchronized(this)，锁定的是Demo03对象的实例
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "已获取锁");
        count--;
        System.out.println(Thread.currentThread().getName() + " count = " + count);
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new SyncAddRunnable(null));
        Thread thread2 = new Thread(new SyncAddRunnable(null));

        thread1.setName("thread1");
        thread2.setName("thread2");

        thread1.start();
        thread2.start();

        Demo002_03 demo002_03 = new Demo002_03();

        thread1 = new Thread(new SyncAddRunnable(demo002_03));
        thread2 = new Thread(new SyncAddRunnable(demo002_03));

        thread1.setName("thread3");
        thread2.setName("thread4");

        thread1.start();
        thread2.start();
    }

    public static class SyncAddRunnable implements Runnable {

        Demo002_03 demo002_03;

        public SyncAddRunnable(Demo002_03 demo002_03) {
            this.demo002_03 = demo002_03;
        }

        @Override
        public void run() {
            System.out.println(String.format("运行线程开始-" + Thread.currentThread().getName()));
            if (demo002_03 == null) {
                demo002_03 = new Demo002_03();
            }
            demo002_03.test();
            System.out.println(String.format("运行线程结束-" + Thread.currentThread().getName()));
        }
    }
}
